export const USER = 'USER'
export const PRINTER = 'PRINTER'
export const STATION_ADMIN = 'STATION_ADMIN'
export const SUPER_ADMIN = 'SUPER_ADMIN'

const setCookie = (cname, cvalue, exdays) => {
  let d = new Date()
  d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000))
  let expires = 'expires=' + d.toUTCString()
  document.cookie = cname + '=' + cvalue + ';' + expires + ';Domain=' + window.location.hostname + ';path=/'
}

const getCookie = cname => {
  let name = cname + '='
  let ca = document.cookie.split(';')
  for (let i = 0; i < ca.length; i++) {
    let c = ca[i]
    while (c.charAt(0) === ' ') {
      c = c.substring(1)
    }
    if (c.indexOf(name) === 0) {
      return c.substring(name.length, c.length)
    }
  }
  return ''
}

export const deleteCookie = () => {
  setCookie('token', '', -1)
  // setCookie('admin', '', -1)
  setCookie('userId', '', -1)
  setCookie('roles', '', -1)
}

export const checkCookie = () => {
  let token = getCookie('token')
  // let admin = getCookie('admin')
  let userId = getCookie('userId')
  let roles = getCookie('roles')
  return token && roles && userId
}

export const level = () => {
  // let admin = getCookie('admin')
  // console.log(admin)
  // let isSuper = getCookie('super')
  // console.log(isSuper)
  // let printer = getCookie('printer')
  // console.log(printer)
  let roles = getCookie('roles').split('#')
  let admin = roles.includes('STATION_ADMIN')
  let isSuper = roles.includes('SUPER_ADMIN')
  let printer = roles.includes('PRINTER')

  if (isSuper) {
    return SUPER_ADMIN
  }

  if (admin) {
    return STATION_ADMIN
  }

  if (printer) {
    return PRINTER
  }

  return USER
}
